package com.photoeditor.demo.ui.widget.image.emoji;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.DashPathEffect;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

import com.common.base.ComponentContext;
import com.common.base.utils.DeviceUtils;
import com.photoeditor.R;
import com.photoeditor.demo.model.bean.EditEmojiBean;
import com.photoeditor.demo.model.bean.EmojiBean;
import com.photoeditor.demo.model.bean.stash.ContainerBean;
import com.photoeditor.demo.model.image.emoji.LocalStickerData;
import com.photoeditor.demo.ui.widget.image.attacher.CanvasPhotoViewAttacher;
import com.photoeditor.demo.ui.widget.image.attacher.IPhotoView;
import com.photoeditor.demo.ui.widget.image.compose.ICanvasEditListener;
import com.photoeditor.demo.ui.widget.stash.container.ContainerView;
import com.photoeditor.demo.util.ImageRectUtils;
import com.photoeditor.demo.util.TouchUtil;

import java.util.LinkedList;

/**
 * 添加Emoji的View
 */
public class CanvasEditEmojiView extends AppCompatImageView implements IPhotoView, IStickerSetting {
    //原来的Bitmap
    private Bitmap mSrcBitmap;
    private Bitmap mCacheBitmap;

    //用于标识是否初始化
    private boolean mIsInit = false;

    //本界面的Bound Rect
    private RectF mRect;

    //Drawable的Bound Rect  默认
    private RectF mDrawableRect;

    /**
     * 需要维护整个List的顺序层次一致
     */

    //存储当前所有Emoji的数据体
    private LinkedList<ContainerBean> mBeans;

    //当前选中的index
    private int mSelectIndex;
    /**
     * ontouch event 相关代码
     */

    //touch down 的坐标
    private float mDownX;
    private float mDownY;

    /*各种移动的模式*/
    private int mMode;

    /*点击*/
    private boolean mIsClick = false;

    /*点击*/
    private boolean mIsClickDelete = false;

    private boolean mIsClickSetting = false;

    //当前已经选中直接移动
    public static final int MODE_MOVE = 1;

    //当前已经选中直接旋转或者缩放
    public static final int MODE_SCALE_OR_ROTATION = 2;

    //当前未选中  需要先选中让后再移动
    public static final int MODE_SELECT_MOVE = 3;

    //未选中
    public static final int MODE_SELECT_NONE = 4;

    public static final int MODE_SELECT_LEFT_OPERATION = 5;
    public static final int MODE_SELECT_RIGHT_OPERATION = 6;
    public static final int MODE_SELECT_TOP_OPERATION = 7;
    public static final int MODE_SELECT_BOTTOM_OPERATION = 8;
    private static final int MODE_SCALE_OR_ROTATION_OR_MOVE = 9;

    //无操作
    public static final int MODE_NONE = -1;

    //用于更新视图
    public static final int DO_ON_DRAW = 0x101;

    //当前选中的EditTextBean
    private ContainerBean mCurrentTouchBean;

    private Paint mBoundPaint;

    //回调
    private ICanvasEditListener mListener;

    //操作Drawable
    private Drawable mOperationDrawable;

    private Drawable mSettingDrawable;

    //操作Drawable
    private Drawable mDeleteDrawable;

    //操作Drawable
    private Drawable mTouchLeftDrawable;
    private Drawable mTouchRightDrawable;
    private Drawable mTouchTopDrawable;
    private Drawable mTouchBottomDrawable;

    //用于缓存绘制时的RectF
    private RectF mCacheRect;

    /**
     * 用于标识当前有PopView不能绘制
     */
    private boolean mHasPopView;

    private boolean mHaveSetting = false;

    private StickerEditListener mStickerEditListener;
    private StickerEditSettingListener mStickerEditSettingListener;

    /**
     * 处理更新
     */
    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(android.os.Message msg) {
            if (msg.what == DO_ON_DRAW) {
                postInvalidate();
            }
        }

        ;
    };

    private final CanvasPhotoViewAttacher mAttacher;

    private Matrix mCacheMatrix;

    private boolean mNeedNotScale = true;

    //是否有原图 拍摄页没有原图 用于原图缩放
    private boolean mHaveSrcBitmap = true;

    //图片的画笔
    private Paint mBitmapPaint;

    //是否画边框
    private boolean mDrawOther = true;
    //开始画路径
    private boolean mStartPaint = false;
    //能够画路径
    private boolean mCanPaint = true;

    private boolean mIsSettingMode = false;

    //一次事件down-->move-->up 可以移动
    private boolean mIsMove = false;

    private CanvasPhotoViewAttacher.OnMatrixChangedListener mMatrixChangeListener = new CanvasPhotoViewAttacher.OnMatrixChangedListener() {
        @Override
        public void onMatrixChanged(RectF rect) {
            if (mDrawableRect == null) {
                mDrawableRect = new RectF();
            }
            mDrawableRect.set(rect);
            if (mIsInit) {
                mDrawableRect.offset(mRect.left, mRect.top);
                countScaleAndDo();
            }
            refresh();
        }
    };
    private DashPathEffect mDashPathEffect;

    public CanvasEditEmojiView(Context context) {
        this(context, null, 0);
    }

    public CanvasEditEmojiView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CanvasEditEmojiView(Context context, AttributeSet attrs,
                               int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        super.setScaleType(ScaleType.MATRIX);
        mAttacher = new CanvasPhotoViewAttacher(this);
        setOnMatrixChangeListener(mMatrixChangeListener);
        initialize();
    }


    private void initialize() {
        setWillNotDraw(false);
        if (isHardwareAccelerated()) {
            setLayerType(View.LAYER_TYPE_HARDWARE, null);
        }
        mCacheMatrix = new Matrix();
        mOperationDrawable = getResources().getDrawable(R.drawable.ic_rotate);
        if (mHaveSetting) {
            mSettingDrawable = getResources().getDrawable(R.drawable.ic_sticker_setting);
        }
        mDeleteDrawable = getResources().getDrawable(R.drawable.ic_close_emoji);
        mTouchLeftDrawable = getResources().getDrawable(R.drawable.ic_touch_move_left);
        mTouchRightDrawable = getResources().getDrawable(R.drawable.ic_touch_move_right);
        mTouchTopDrawable = getResources().getDrawable(R.drawable.ic_touch_move_top);
        mTouchBottomDrawable = getResources().getDrawable(R.drawable.ic_touch_move_bottom);
        mCacheRect = new RectF();
        setMaximumScale(8.0f);
        setMediumScale(1.0f);

        mBoundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBoundPaint.setColor(getResources().getColor(R.color.image_edit_text_bound_color));
        mBoundPaint.setAntiAlias(true);
        mBoundPaint.setStrokeWidth(DeviceUtils.dip2px(ComponentContext.getContext(), 1));
        mBoundPaint.setStyle(Style.STROKE);
        mBeans = new LinkedList<>();
        mSelectIndex = -1;

        mBitmapPaint = new Paint();
        mBitmapPaint.setAntiAlias(true);
        mBitmapPaint.setFilterBitmap(true);

        mRingPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mRingPaint.setStyle(Paint.Style.STROKE);
        mRingPaint.setColor(Color.WHITE);
        mRingPaint.setStrokeWidth(DeviceUtils.dip2px(ComponentContext.getContext(), 2));

        mCirclePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCirclePaint.setStyle(Paint.Style.FILL);
        mCirclePaint.setColor(Color.parseColor("#33000000"));

        float dp1 = DeviceUtils.dip2px(ComponentContext.getContext(), 2);
        mDashPathEffect = new DashPathEffect(new float[]{dp1, dp1}, 1);
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
        super.setImageBitmap(bm);
        if (mSrcBitmap == null || mSrcBitmap != bm) {
            mIsInit = false;
        }
        mSrcBitmap = bm;
        if (null != mAttacher) {
            mAttacher.update();
        }
    }

    @Override
    public void setImageDrawable(Drawable drawable) {
        super.setImageDrawable(drawable);
        if (drawable instanceof BitmapDrawable) {
            Bitmap bm = ((BitmapDrawable) drawable).getBitmap();
            if (mSrcBitmap == null || mSrcBitmap != bm) {
                mIsInit = false;
            }
            mSrcBitmap = bm;
            if (null != mAttacher) {
                mAttacher.update();
            }
        }
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right,
                            int bottom) {
        super.onLayout(changed, left, top, right, bottom);

        if (!mIsInit) {
            init(ImageRectUtils.getViewRect(this));
        }
    }

    public void forceInit(RectF rect) {
        init(rect);
    }

    /**
     * 初始化这个类   这个方法在使用前必须调用 ！！！！！
     *
     * @param rect 整个View的Rect
     */
    public void init(RectF rect) {

        float width = rect.width();
        if (rect.left == width) {
            rect.left = 0;
            rect.right = width;
        }

        mRect = rect;
        centerX = mRect.centerX();
        centerY = mRect.centerY();
        if (mHaveSrcBitmap) {
            if (mSrcBitmap == null || mSrcBitmap.isRecycled()) {
                mIsInit = false;
                return;
            }
            countDrawableInitPosition(rect);
            mBaseDrawableRect = new RectF(0, 0, getDrawable().getIntrinsicWidth(), getDrawable().getIntrinsicHeight());
        }
        if (mDrawableRect != null) {
            mDrawableRect.offset(mRect.left, mRect.top);
        }
//			mBaseDrawableRect.offset(mRect.left, mRect.top);
//			mDrawableRect = dRect

        mIsInit = true;

    }

    /**
     * 先绘制未选中的  然后绘制选中的
     */
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (mHaveSrcBitmap) {
            if (mSrcBitmap == null || mSrcBitmap.isRecycled()) {
                return;
            }
        }
        int len = mBeans.size();
        for (int i = 0; i < len; i++) {
            if (i != mSelectIndex) {
                ContainerBean bean = mBeans.get(i);
                RectF dst = bean.getRect();
//				RectF nnn = new RectF();
//				EditEmojiBean.doScale(dst, nnn, mBaseDrawableRect, mSupportDrawableRect, getImageMatrix(), mCacheMatrix, mRect);
                mCacheRect.left = dst.left - mRect.left;
                mCacheRect.top = dst.top - mRect.top;
                mCacheRect.right = dst.right - mRect.left;
                mCacheRect.bottom = dst.bottom - mRect.top;
                int count = canvas.save();
                if (mHaveSrcBitmap && !bean.isTouch()) {
                    canvas.clipRect(mDrawableRect.left - mRect.left, mDrawableRect.top - mRect.top, mDrawableRect.right - mRect.left, mDrawableRect.bottom - mRect.top);
                }
                canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());
                if (bean.getType() == ContainerView.BEAN_TYPE_STICKER) {
                    mBitmapPaint.setColorFilter(generateColorMatrixColorFilter((EditEmojiBean) bean));
                } else {
                    mBitmapPaint.setColorFilter(null);
                }
                canvas.scale(bean.getFlipX(), bean.getFlipY(), mCacheRect.centerX(), mCacheRect.centerY());
                if (bean.getBitmap() != null && !bean.getBitmap().isRecycled()) {
                    canvas.drawBitmap(bean.getBitmap(), null, mCacheRect, mBitmapPaint);
                }
                canvas.restoreToCount(count);
            } else {
                ContainerBean bean = mBeans.get(mSelectIndex);
                RectF dst = bean.getRect();
                RectF br = bean.getButtonRect();
                RectF sr = bean.getSettingRect();
                RectF dr = bean.getDeleteRect();
                RectF leftR = bean.getLeftOperationRect();
                RectF rightR = bean.getRightOperationRect();
                RectF topR = bean.getTopOperationRect();
                RectF bottomR = bean.getBottomOperationRect();
                mCacheRect.left = dst.left - mRect.left;
                mCacheRect.top = dst.top - mRect.top;
                mCacheRect.right = dst.right - mRect.left;
                mCacheRect.bottom = dst.bottom - mRect.top;
                int count1 = canvas.save();
                if (mHaveSrcBitmap && !bean.isTouch()) {
                    canvas.clipRect(mDrawableRect.left - mRect.left, mDrawableRect.top - mRect.top, mDrawableRect.right - mRect.left, mDrawableRect.bottom - mRect.top);
                }
                canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());
                if (bean.getType() == ContainerView.BEAN_TYPE_STICKER) {
                    mBitmapPaint.setColorFilter(generateColorMatrixColorFilter((EditEmojiBean) bean));
                } else {
                    mBitmapPaint.setColorFilter(null);
                }
                canvas.scale(bean.getFlipX(), bean.getFlipY(), mCacheRect.centerX(), mCacheRect.centerY());
                if (bean.getBitmap() != null && !bean.getBitmap().isRecycled()) {
                    canvas.drawBitmap(bean.getBitmap(), null, mCacheRect, mBitmapPaint);
                }
                canvas.restoreToCount(count1);

                if (mIsSettingMode) {
                    if (bean.getType() == ContainerView.BEAN_TYPE_STICKER) {
                        int count2 = canvas.save();
                        canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());
                        mBoundPaint.setPathEffect(mDashPathEffect);
                        canvas.drawRect(mCacheRect, mBoundPaint);
                        mBoundPaint.setPathEffect(null);
                        canvas.restoreToCount(count2);
                    }
                } else {
                    if (mDrawOther && mMode != MODE_SCALE_OR_ROTATION_OR_MOVE) {
                        int count2 = canvas.save();
                        canvas.rotate(bean.getDegree(), mCacheRect.centerX(), mCacheRect.centerY());
                        canvas.drawRect(mCacheRect, mBoundPaint);
                        if (mMode == MODE_SCALE_OR_ROTATION) {
                            mOperationDrawable.setBounds((int) (br.left - mRect.left + 0.5f), (int) (br.top - mRect.top + 0.5f), (int) (br.right - mRect.left + 0.5f), (int) (br.bottom - mRect.top + 0.5f));
                            mOperationDrawable.draw(canvas);
                        } else if (mMode == MODE_SELECT_LEFT_OPERATION || mMode == MODE_SELECT_RIGHT_OPERATION) {
                            mTouchLeftDrawable.setBounds((int) (leftR.left - mRect.left + 0.5f), (int) (leftR.top - mRect.top + 0.5f), (int) (leftR.right - mRect.left + 0.5f), (int) (leftR.bottom - mRect.top + 0.5f));
                            mTouchLeftDrawable.draw(canvas);
                            mTouchRightDrawable.setBounds((int) (rightR.left - mRect.left + 0.5f), (int) (rightR.top - mRect.top + 0.5f), (int) (rightR.right - mRect.left + 0.5f), (int) (rightR.bottom - mRect.top + 0.5f));
                            mTouchRightDrawable.draw(canvas);
                        } else if (mMode == MODE_SELECT_TOP_OPERATION || mMode == MODE_SELECT_BOTTOM_OPERATION) {
                            mTouchTopDrawable.setBounds((int) (topR.left - mRect.left + 0.5f), (int) (topR.top - mRect.top + 0.5f), (int) (topR.right - mRect.left + 0.5f), (int) (topR.bottom - mRect.top + 0.5f));
                            mTouchTopDrawable.draw(canvas);
                            mTouchBottomDrawable.setBounds((int) (bottomR.left - mRect.left + 0.5f), (int) (bottomR.top - mRect.top + 0.5f), (int) (bottomR.right - mRect.left + 0.5f), (int) (bottomR.bottom - mRect.top + 0.5f));
                            mTouchBottomDrawable.draw(canvas);
                        } else {
                            mOperationDrawable.setBounds((int) (br.left - mRect.left + 0.5f), (int) (br.top - mRect.top + 0.5f), (int) (br.right - mRect.left + 0.5f), (int) (br.bottom - mRect.top + 0.5f));
                            mOperationDrawable.draw(canvas);
                            if (mHaveSetting && bean.getType() == ContainerView.BEAN_TYPE_STICKER) {
                                mSettingDrawable.setBounds((int) (sr.left - mRect.left + 0.5f), (int) (sr.top - mRect.top + 0.5f), (int) (sr.right - mRect.left + 0.5f), (int) (sr.bottom - mRect.top + 0.5f));
                                mSettingDrawable.draw(canvas);
                            }
                            mDeleteDrawable.setBounds((int) (dr.left - mRect.left + 0.5f), (int) (dr.top - mRect.top + 0.5f), (int) (dr.right - mRect.left + 0.5f), (int) (dr.bottom - mRect.top + 0.5f));
                            mDeleteDrawable.draw(canvas);
                            mTouchLeftDrawable.setBounds((int) (leftR.left - mRect.left + 0.5f), (int) (leftR.top - mRect.top + 0.5f), (int) (leftR.right - mRect.left + 0.5f), (int) (leftR.bottom - mRect.top + 0.5f));
                            mTouchLeftDrawable.draw(canvas);
                            mTouchRightDrawable.setBounds((int) (rightR.left - mRect.left + 0.5f), (int) (rightR.top - mRect.top + 0.5f), (int) (rightR.right - mRect.left + 0.5f), (int) (rightR.bottom - mRect.top + 0.5f));
                            mTouchRightDrawable.draw(canvas);
                            mTouchTopDrawable.setBounds((int) (topR.left - mRect.left + 0.5f), (int) (topR.top - mRect.top + 0.5f), (int) (topR.right - mRect.left + 0.5f), (int) (topR.bottom - mRect.top + 0.5f));
                            mTouchTopDrawable.draw(canvas);
                            mTouchBottomDrawable.setBounds((int) (bottomR.left - mRect.left + 0.5f), (int) (bottomR.top - mRect.top + 0.5f), (int) (bottomR.right - mRect.left + 0.5f), (int) (bottomR.bottom - mRect.top + 0.5f));
                            mTouchBottomDrawable.draw(canvas);
                        }
                        canvas.restoreToCount(count2);
                    }
                }
            }
        }
        if (mSelectIndex < len && mSelectIndex >= 0) {
            ContainerBean bean = mBeans.get(mSelectIndex);
            if (bean instanceof EditEmojiBean) {
                drawPaintWidthCircle(canvas, ((EditEmojiBean) bean).getPaintWidthRadius());
                drawPathCircle(canvas, ((EditEmojiBean) bean).getPaintWidthRadius());
            }
        }

    }

    private boolean mDrawPaintWidthCircle = false;
    private boolean mDrawPathCircle = false;
    private Paint mRingPaint;
    private Paint mCirclePaint;

    public void setDrawPaintWidthCircle(boolean drawPaintWidthCircle) {
        mDrawPaintWidthCircle = drawPaintWidthCircle;
    }

    //画笔宽度示意图
    private void drawPaintWidthCircle(Canvas canvas, float radius) {
        if (mDrawPaintWidthCircle) {
            canvas.drawCircle(centerX - mRect.left, centerY - mRect.top, radius, mCirclePaint);
            canvas.drawCircle(centerX - mRect.left, centerY - mRect.top, radius, mRingPaint);
        }
    }

    //画笔示意图
    private void drawPathCircle(Canvas canvas, float radius) {
        if (mDrawPathCircle) {
            canvas.drawCircle(mDownX - mRect.left, mDownY - mRect.top, radius, mRingPaint);
        }
    }

    public ColorMatrixColorFilter generateColorMatrixColorFilter(EditEmojiBean bean) {
        if (bean.isShowSrc()) {
            EditEmojiBean.AdjustParam lastParam = bean.getLastParam();
            ColorMatrix hueMatrix = new ColorMatrix();
            //修改色相   0 red 1 green 2 blue
            hueMatrix.setRotate(0, 0);
            hueMatrix.setRotate(1, 0);
            hueMatrix.setRotate(2, 0);
            //修改饱和度
            ColorMatrix saturationMatrix = new ColorMatrix();
            saturationMatrix.setSaturation(1);
            //修改亮度
            ColorMatrix lumMatrix = new ColorMatrix();
            //r g b a    1 表示全不透明
            lumMatrix.setScale(1, 1, 1, 1 - 0);

            //组合Matrix
            ColorMatrix imageMatrix = new ColorMatrix();
            imageMatrix.postConcat(hueMatrix);
            imageMatrix.postConcat(saturationMatrix);
            imageMatrix.postConcat(lumMatrix);

            return new ColorMatrixColorFilter(imageMatrix);
        } else {
            EditEmojiBean.AdjustParam lastParam = bean.getLastParam();
            ColorMatrix hueMatrix = new ColorMatrix();
            //修改色相   0 red 1 green 2 blue
            hueMatrix.setRotate(0, lastParam.tone);
            hueMatrix.setRotate(1, lastParam.tone);
            hueMatrix.setRotate(2, lastParam.tone);
            //修改饱和度
            ColorMatrix saturationMatrix = new ColorMatrix();
            saturationMatrix.setSaturation(lastParam.saturation);
            //修改亮度
            ColorMatrix lumMatrix = new ColorMatrix();
            //r g b a    1 表示全不透明
            lumMatrix.setScale(lastParam.brightness, lastParam.brightness, lastParam.brightness, 1 - lastParam.alpha);

            //组合Matrix
            ColorMatrix imageMatrix = new ColorMatrix();
            imageMatrix.postConcat(hueMatrix);
            imageMatrix.postConcat(saturationMatrix);
            imageMatrix.postConcat(lumMatrix);

            return new ColorMatrixColorFilter(imageMatrix);
        }
    }

    /**
     * Ontouchevent中调用 用于获取当前选中的对象
     * 这个会切换选中对象
     * 如果切换成功，层次关系需要修改
     * <p>
     * x y是点击的真实坐标
     *
     * @param x
     * @param y
     * @param distinguishSticker 只计算表情
     * @return
     */
    private int getTouchEditTextBeanIndex(float x, float y, boolean distinguishSticker) {
        if (mBeans != null) {
            int len = mBeans.size();
            for (int i = len - 1; i >= 0; i--) {
                ContainerBean bean = mBeans.get(i);
                if (distinguishSticker && bean.getType() != ContainerView.BEAN_TYPE_STICKER) {
                    continue;
                }
                //dst用于存储变换后的点
                float[] dst = new float[2];
                bean.getMatrix().mapPoints(dst, new float[]{x, y});
                RectF vr = bean.getRect();
                if (vr.contains(dst[0], dst[1])) {//匹配成功  需要布局层次关系
                    //把将要选中的放到最后  绘制的时候就会正确
                    mBeans.remove(i);
                    mBeans.addLast(bean);
                    return (len - 1);
                }
            }
        }
        return -1;
    }

    //滑动了的路径
    private boolean mIsUsefulPath;

    float oldDist = 1f;
    float oldRotation = 0;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (!mIsInit) return super.onTouchEvent(event);
        if (mHasPopView) {//当存在PopView是拦截掉
            // 触发事件
            if (mListener != null) {
                /**
                 * 用于关闭PopView
                 */
                mListener.onTouchDown(0);
            }
            return false;
        }
        switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_POINTER_DOWN:
                oldDist = spacing(event);
                oldRotation = rotation(event);
                int pos = getTouchEditTextBeanIndex(event.getX(0), event.getY(0), false);
                if (pos != -1) {
                    mMode = MODE_SCALE_OR_ROTATION_OR_MOVE;
                    mIsClick = true;
                    mSelectIndex = pos;
                    mCurrentTouchBean = mBeans.get(mSelectIndex);
                    mCurrentTouchBean.setIsTouch(true);
                    refresh();
                    return true;
                } else {
                    if (mHaveSrcBitmap && !mNeedNotScale) {
                        mAttacher.onTouch(this, event);
                    }
                    mMode = MODE_SELECT_NONE;
                }
                break;
            case MotionEvent.ACTION_DOWN:
                mAttacher.setCanDrag(true);
                mDrawOther = true;
                mIsMove = false;
                if (mIsSettingMode && !mCanPaint) {
                    //参数调节触摸贴纸也可以缩放
                    mNeedNotScale = false;
                } else {
                    mNeedNotScale = true;
                }
                if (mListener != null) {
                    mListener.onTouchDown(1);
                }
                mDownX = event.getRawX();
                mDownY = event.getY();

                if (mSelectIndex >= 0 && mSelectIndex < mBeans.size()) {
                    //先进行变换然后判断点击区域
                    mCurrentTouchBean = mBeans.get(mSelectIndex);
                    //dst用于存储变换后的点
                    float[] dst = new float[2];
                    mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});
                    RectF vr = mCurrentTouchBean.getRect();

                    RectF leftOperationRect = mCurrentTouchBean.getLeftOperationRect();
                    RectF rightOperationRect = mCurrentTouchBean.getRightOperationRect();
                    RectF topOperationRect = mCurrentTouchBean.getTopOperationRect();
                    RectF bottomOperationRect = mCurrentTouchBean.getBottomOperationRect();

                    float d = (float) Math.sqrt((dst[0] - vr.right) * (dst[0] - vr.right) + (dst[1] - vr.bottom) * (dst[1] - vr.bottom));

                    float deleteDistance = (float) Math.sqrt((dst[0] - vr.left) * (dst[0] - vr.left) + (dst[1] - vr.top) * (dst[1] - vr.top));

                    float settingDistance = (float) Math.sqrt((dst[0] - vr.left) * (dst[0] - vr.left) + (dst[1] - vr.bottom) * (dst[1] - vr.bottom));

                    if (mIsSettingMode) {
                        if (vr.contains(dst[0], dst[1])) {
                            if (mCanPaint) {
                                //涂鸦下  放大后不可以拖动
                                mAttacher.setCanDrag(false);
                                mStartPaint = true;
                                mIsUsefulPath = false;
                                mDrawPathCircle = false;
                                ((EditEmojiBean) mCurrentTouchBean).setPathStart(mDownX - vr.left, mDownY - vr.top);
                            }
                            mCurrentTouchBean.setIsTouch(true);
                            mIsClick = true;
                            mMode = MODE_SELECT_NONE;
                            refresh();
                            if (mHaveSrcBitmap) {
                                //支持双击方法
                                mAttacher.onTouch(this, event);
                            }
                            return true;
                        } else {
                            int index = getTouchEditTextBeanIndex(mDownX, mDownY, true);
                            if (index != -1) {
                                mIsClick = true;
                                mSelectIndex = index;
                                mCurrentTouchBean = mBeans.get(mSelectIndex);
                                mCurrentTouchBean.setIsTouch(true);
                                refresh();
                                mMode = MODE_SELECT_NONE;
                                if (mStickerEditSettingListener != null) {
                                    mStickerEditSettingListener.onSelectOther(mCurrentTouchBean);
                                }
                                if (mHaveSrcBitmap) {
                                    mAttacher.onTouch(this, event);
                                }
                                return true;
                            } else {
                                mMode = MODE_SELECT_NONE;
                                mDrawOther = false;
                                if (mHaveSrcBitmap) {
                                    mAttacher.onTouch(this, event);
                                }
                                mNeedNotScale = false;
                                if (mHaveSrcBitmap) {
                                    return true;
                                }
                            }
                        }
                    } else {
                        if (mSelectIndex == mBeans.size() - 1) {
                            if (vr.contains(dst[0], dst[1])) {//Rect内
                                if (d <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {//按钮
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SCALE_OR_ROTATION;
                                } else if (deleteDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mIsClickDelete = true;
                                } else if (mHaveSetting && settingDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mIsClickSetting = true;
                                } else if (leftOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_LEFT_OPERATION;
                                } else if (rightOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_RIGHT_OPERATION;
                                } else if (topOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_TOP_OPERATION;
                                } else if (bottomOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_BOTTOM_OPERATION;
                                } else {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_MOVE;
                                    mIsClick = true;
                                }
                                return true;
                            } else {
                                if (d <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {//按钮
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SCALE_OR_ROTATION;
                                    return true;
                                } else if (mHaveSetting && settingDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mIsClickSetting = true;
                                } else if (deleteDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mIsClickDelete = true;
                                    return true;
                                } else if (leftOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_LEFT_OPERATION;
                                    return true;
                                } else if (rightOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_RIGHT_OPERATION;
                                    return true;
                                } else if (topOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_TOP_OPERATION;
                                    return true;
                                } else if (bottomOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_BOTTOM_OPERATION;
                                    return true;
                                } else {
                                    //判断它点到的区域属于哪一个bean
                                    int index = getTouchEditTextBeanIndex(mDownX, mDownY, false);
                                    if (index != -1) {//重定位
                                        mSelectIndex = index;
                                        mCurrentTouchBean = mBeans.get(mSelectIndex);
                                        mCurrentTouchBean.setIsTouch(true);
                                        refresh();
                                        mMode = MODE_SELECT_MOVE;
                                        if (mListener != null) {
                                            mListener.onSelected();
                                        }
                                        return true;
                                    } else {//没有选中其他区域
                                        mMode = MODE_SELECT_NONE;
                                        mDrawOther = false;
                                        mSelectIndex = -1;
                                        if (mHaveSrcBitmap) {
                                            mAttacher.onTouch(this, event);
                                        }
                                        mNeedNotScale = false;
                                    }
                                }
                            }
                        } else {

                            //图层下移了
                            //判断它点到的区域属于哪一个bean
                            int index = getTouchEditTextBeanIndex(mDownX, mDownY, false);
                            if (index != -1) {//重定位
                                if (mCurrentTouchBean == mBeans.get(index)) {
                                    //在下层操作按钮响应 内部
                                    if (vr.contains(dst[0], dst[1])) {//Rect内
                                        if (d <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {//按钮
                                            mCurrentTouchBean.setIsTouch(true);
                                            refresh();
                                            mMode = MODE_SCALE_OR_ROTATION;
                                        } else if (deleteDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                            mCurrentTouchBean.setIsTouch(true);
                                            refresh();
                                            mIsClickDelete = true;
                                        } else if (mHaveSetting && settingDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                            mCurrentTouchBean.setIsTouch(true);
                                            refresh();
                                            mIsClickSetting = true;
                                        } else if (leftOperationRect.contains(dst[0], dst[1])) {
                                            mCurrentTouchBean.setIsTouch(true);
                                            refresh();
                                            mMode = MODE_SELECT_LEFT_OPERATION;
                                        } else if (rightOperationRect.contains(dst[0], dst[1])) {
                                            mCurrentTouchBean.setIsTouch(true);
                                            refresh();
                                            mMode = MODE_SELECT_RIGHT_OPERATION;
                                        } else if (topOperationRect.contains(dst[0], dst[1])) {
                                            mCurrentTouchBean.setIsTouch(true);
                                            refresh();
                                            mMode = MODE_SELECT_TOP_OPERATION;
                                        } else if (bottomOperationRect.contains(dst[0], dst[1])) {
                                            mCurrentTouchBean.setIsTouch(true);
                                            refresh();
                                            mMode = MODE_SELECT_BOTTOM_OPERATION;
                                        } else {
                                            mCurrentTouchBean.setIsTouch(true);
                                            refresh();
                                            mMode = MODE_MOVE;
                                            mIsClick = true;
                                        }
                                        mSelectIndex = index;
                                        return true;
                                    }
                                } else {
                                    mSelectIndex = index;
                                    mCurrentTouchBean = mBeans.get(mSelectIndex);
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_MOVE;
                                    if (mListener != null) {
                                        mListener.onSelected();
                                    }
                                    return true;
                                }
                            } else {//没有选中其他区域
                                //在下层操作按钮响应 外部
                                if (d <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {//按钮
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SCALE_OR_ROTATION;
                                    return true;
                                } else if (mHaveSetting && settingDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mIsClickSetting = true;
                                } else if (deleteDistance <= EditEmojiBean.RADIUS + TouchUtil.TOUCH_BUTTON_OFFSET) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mIsClickDelete = true;
                                    return true;
                                } else if (leftOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_LEFT_OPERATION;
                                    return true;
                                } else if (rightOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_RIGHT_OPERATION;
                                    return true;
                                } else if (topOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_TOP_OPERATION;
                                    return true;
                                } else if (bottomOperationRect.contains(dst[0], dst[1])) {
                                    mCurrentTouchBean.setIsTouch(true);
                                    refresh();
                                    mMode = MODE_SELECT_BOTTOM_OPERATION;
                                    return true;
                                } else {
                                    mMode = MODE_SELECT_NONE;
                                    mDrawOther = false;
                                    mSelectIndex = -1;
                                    if (mHaveSrcBitmap) {
                                        mAttacher.onTouch(this, event);
                                    }
                                    mNeedNotScale = false;
                                }
                            }
                        }
                        if (mHaveSrcBitmap) {
                            return true;
                        }
                    }
                } else {//当前未选中    这种是特殊处理 一般不可能没有选中项的
                    //判断它点到的区域属于哪一个bean
                    int index = getTouchEditTextBeanIndex(mDownX, mDownY, false);
                    if (index != -1) {
                        mSelectIndex = index;
                        mCurrentTouchBean = mBeans.get(mSelectIndex);
                        mCurrentTouchBean.setIsTouch(true);
                        refresh();
                        mMode = MODE_SELECT_MOVE;
                        if (mListener != null) {
                            mListener.onSelected();
                        }
                        return true;
                    } else {//没有选中其他区域
                        mMode = MODE_SELECT_NONE;
                        mSelectIndex = -1;
                        mDrawOther = false;
                        mAttacher.onTouch(this, event);
                        mNeedNotScale = false;
                    }
                    if (mHaveSrcBitmap) {
                        return true;
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (mHaveSrcBitmap && mMode == MODE_SELECT_NONE && !mIsClick) {
                    mAttacher.onTouch(this, event);
                }
                if (!mIsSettingMode && mMode == MODE_SCALE_OR_ROTATION_OR_MOVE) {
                    float newDist = spacing(event);
                    if (mIsClick && Math.abs(newDist - oldDist) <= ViewConfiguration.getTouchSlop()) {
                        return true;
                    }
                    mIsClick = false;
                    float rotation = rotation(event) - oldRotation;
                    float scale = newDist / oldDist;
                    mCurrentTouchBean.setDegree(rotation);
                    mCurrentTouchBean.setScale(scale);
                    oldRotation = rotation(event);
                    oldDist = newDist;
                    refresh();
                    return true;
                }
                float nowX = event.getRawX();
                float nowY = event.getY();

                float dx = nowX - mDownX;
                float dy = nowY - mDownY;
                if (mIsMove || Math.abs(dx) >= TouchUtil.OFFSET || Math.abs(dy) >= TouchUtil.OFFSET) {
                    mIsMove = true;
                    if (mIsSettingMode && mStartPaint) {
                        mIsClick = false;
                        mIsUsefulPath = true;
                        mDrawPathCircle = true;
                        RectF vr = mCurrentTouchBean.getRect();
                        ((EditEmojiBean) mCurrentTouchBean).setPathMove(mDownX - vr.left, mDownY - vr.top, nowX - vr.left, nowY - vr.top);
                        mDownX = nowX;
                        mDownY = nowY;
                        refresh();

                    } else {
                        mIsClick = false;
                        mIsClickDelete = false;
                        mIsClickSetting = false;
                        if (mMode == MODE_MOVE || mMode == MODE_SELECT_MOVE) {
                            mCurrentTouchBean.move(dx, dy);
                            mDownX = nowX;
                            mDownY = nowY;
                            refresh();
                        } else if (mMode == MODE_SCALE_OR_ROTATION) {
                            mCurrentTouchBean.dealScaleAndRotation(mDownX, mDownY, nowX, nowY);
                            mDownX = nowX;
                            mDownY = nowY;
                            refresh();
                        } else if (mMode == MODE_SELECT_LEFT_OPERATION) {
                            float[] dst = new float[2];
                            mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});

                            float[] sda = new float[2];
                            mCurrentTouchBean.getMatrix().mapPoints(sda, new float[]{nowX, nowY});

                            dx = sda[0] - dst[0];
                            dy = sda[1] - dst[1];

                            mCurrentTouchBean.operationLeft(dx);
                            mDownX = nowX;
                            mDownY = nowY;
                            refresh();
                        } else if (mMode == MODE_SELECT_RIGHT_OPERATION) {
                            float[] dst = new float[2];
                            mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});

                            float[] sda = new float[2];
                            mCurrentTouchBean.getMatrix().mapPoints(sda, new float[]{nowX, nowY});

                            dx = sda[0] - dst[0];
                            dy = sda[1] - dst[1];

                            mCurrentTouchBean.operationRight(dx);
                            mDownX = nowX;
                            mDownY = nowY;
                            refresh();
                        } else if (mMode == MODE_SELECT_TOP_OPERATION) {
                            float[] dst = new float[2];
                            mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});

                            float[] sda = new float[2];
                            mCurrentTouchBean.getMatrix().mapPoints(sda, new float[]{nowX, nowY});

                            dx = sda[0] - dst[0];
                            dy = sda[1] - dst[1];

                            mCurrentTouchBean.operationTop(dy);
                            mDownX = nowX;
                            mDownY = nowY;
                            refresh();
                        } else if (mMode == MODE_SELECT_BOTTOM_OPERATION) {
                            float[] dst = new float[2];
                            mCurrentTouchBean.getMatrix().mapPoints(dst, new float[]{mDownX, mDownY});

                            float[] sda = new float[2];
                            mCurrentTouchBean.getMatrix().mapPoints(sda, new float[]{nowX, nowY});

                            dx = sda[0] - dst[0];
                            dy = sda[1] - dst[1];

                            mCurrentTouchBean.operationBottom(dy);
                            mDownX = nowX;
                            mDownY = nowY;
                            refresh();
                        } else if (mMode == MODE_SELECT_NONE) {//do nothing
                            refresh();
                        }
                    }
                }
                break;
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_POINTER_UP:
                if (mHaveSrcBitmap && mMode == MODE_SELECT_NONE) {
                    mAttacher.onTouch(this, event);
                }
                if (mCurrentTouchBean != null) {
                    mCurrentTouchBean.setIsTouch(false);
                }
                if (mIsClick) {//点击处理
                    mIsClick = false;
//				if(mClickListener != null){
//					mClickListener.onclick(mCurrentTouchBean);
//				}
                }
                if (mIsClickDelete) {
                    mIsClickDelete = false;
                    deleteEmoji(mSelectIndex);
                }
                if (mIsClickSetting && mCurrentTouchBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
                    mIsClickSetting = false;
                    mIsSettingMode = true;
                    if (mStickerEditListener != null) {
                        mStickerEditListener.onClickSetting();
                    }
                }
                if (!mIsSettingMode) {
                    mMode = MODE_NONE;
                } else {
                    if (mStartPaint && mIsUsefulPath) {
                        mDrawPathCircle = false;
                        ((EditEmojiBean) mCurrentTouchBean).savePath();
                        if (mStickerEditSettingListener != null) {
                            mStickerEditSettingListener.onPaintFinish();
                        }
                    }
                }
                mIsMove = false;
                mStartPaint = false;
                refresh();
                break;
        }
        return super.onTouchEvent(event);
    }

    // 触碰两点间距离
    private float spacing(MotionEvent event) {
        try {
            float x = event.getX(0) - event.getX(1);
            float y = event.getY(0) - event.getY(1);
            return (float) Math.sqrt(x * x + y * y);
        } catch (Exception e) {
            return oldDist;
        }
    }

    // 取旋转角度
    private float rotation(MotionEvent event) {
        try {
            double delta_x = (event.getX(0) - event.getX(1));
            double delta_y = (event.getY(0) - event.getY(1));
            double radians = Math.atan2(delta_y, delta_x);
            return (float) Math.toDegrees(radians);
        } catch (Exception e) {
            return oldRotation;
        }
    }

    /**
     * 添加Emoji表情
     *
     * @param emoji
     */
    public void addEmoji(EmojiBean emoji) {
        if (!mIsInit || emoji == null) return;
        EditEmojiBean bean = null;
        try {
            bean = new EditEmojiBean(centerX, centerY, emoji);
        } catch (Exception e) {
            //这里崩溃意味着该贴纸不可用，不执行下一步动作
            return;
        }
        bean.setLastMatrix(getImageMatrix());
        mBeans.addLast(bean);
        mSelectIndex = mBeans.size() - 1;
        mDrawOther = true;
        refresh();
        if (mListener != null) {
            mListener.onSelected();
            mListener.onNeedSaveChangedTo(true);
            mListener.onAdd(bean);
        }
    }

    public void addGif(String filePath) {
        if (!mIsInit) return;
//        StickerGifBean bean = new StickerGifBean(centerX, centerY, filePath);
//        bean.setOnGifRefreshListener(this);
//        bean.setLastMatrix(getImageMatrix());
//        mBeans.addLast(bean);
//        mSelectIndex = mBeans.size() - 1;
//        mDrawOther = true;
//        refresh();
//        if (mListener != null) {
//            mListener.onSelected();
//            mListener.onNeedSaveChangedTo(true);
//            mListener.onAdd(bean);
//        }
    }

    public void addCanvasBean(ContainerBean bean) {
        mBeans.addLast(bean);
        mSelectIndex = mBeans.size() - 1;
        mDrawOther = true;
        refresh();
        if (mListener != null) {
            mListener.onSelected();
            mListener.onNeedSaveChangedTo(true);
            mListener.onAdd(bean);
        }
    }

    //主界面中心点
    private float centerX = 0;
    private float centerY = 0;

    public void setCenterPoint(float centerX, float centerY) {
        this.centerX = centerX;
        this.centerY = centerY;
    }

    public void setCanPaint(boolean canPaint) {
        mCanPaint = canPaint;
    }

    /**
     * 删除Emoji表情
     *
     * @param position
     */
    public void deleteEmoji(int position) {
        if (position < mBeans.size() && position >= 0) {
            ContainerBean remove = mBeans.remove(position);
            remove.onDestroy();
            int size = mBeans.size();
            mSelectIndex = size - 1;
            refresh();
            if (mListener != null) {
                mListener.onSelected();
                if (size == 0) {
                    mListener.onNeedSaveChangedTo(false);
                }
                mListener.onDelete(remove);
            }
        }
    }

    public void setHaveSrcBitmap(boolean haveSrcBitmap) {
        mHaveSrcBitmap = haveSrcBitmap;
    }

    /**
     * emoji卸载后的处理
     *
     * @param pkgName
     */
    public void removeUninstallSticker(String pkgName) {
        if (mBeans == null) return;
        int size = mBeans.size();
        for (int i = 0; i < size; ) {
            if (mBeans.get(i) instanceof EditEmojiBean) {
                EditEmojiBean editEmojiBean = (EditEmojiBean) mBeans.get(i);
                String beanPkgName = editEmojiBean.getEmojiBean().getPackageName();
                if (beanPkgName != null && beanPkgName.equals(pkgName)) {
                    mBeans.remove(i);
                    size--;
                } else {
                    i++;
                }
            }
        }
        mSelectIndex = mBeans.size() - 1;
        refresh();
        if (mListener != null) {
            mListener.onSelected();
            if (size == 0) {
                mListener.onNeedSaveChangedTo(false);
            }
        }
    }

    public LinkedList<ContainerBean> getBeans() {
        return mBeans;
    }


    ValueAnimator rotateAnimator;

    /**
     * 旋转
     */
    public void doRotate(float degree) {
        if (mSelectIndex != -1) {
            if (rotateAnimator != null && rotateAnimator.isRunning()) {
                rotateAnimator.end();
            }
            mCurrentTouchBean = mBeans.get(mSelectIndex);
            final float degreeBefore = mCurrentTouchBean.getDegree();
            rotateAnimator = ValueAnimator.ofFloat(0, degree);
            rotateAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    mCurrentTouchBean.setDegreeDirect(degreeBefore + (Float) animation.getAnimatedValue());
                    refresh();
                }
            });
            rotateAnimator.setDuration(200);
            rotateAnimator.start();
        }
    }

    public void doFlip(final boolean horizontal) {
        if (mSelectIndex != -1) {
            if (rotateAnimator != null && rotateAnimator.isRunning()) {
                rotateAnimator.end();
            }
            mCurrentTouchBean = mBeans.get(mSelectIndex);
            if (horizontal) {
                if (mCurrentTouchBean.getFlipX() == 1) {
                    rotateAnimator = ValueAnimator.ofFloat(1, -1);
                } else {
                    rotateAnimator = ValueAnimator.ofFloat(-1, 1);
                }
            } else {
                if (mCurrentTouchBean.getFlipY() == 1) {
                    rotateAnimator = ValueAnimator.ofFloat(1, -1);
                } else {
                    rotateAnimator = ValueAnimator.ofFloat(-1, 1);
                }
            }
            rotateAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    mCurrentTouchBean.setFlip(horizontal, (Float) animation.getAnimatedValue());
                    refresh();
                }
            });
            rotateAnimator.setDuration(200);
            rotateAnimator.start();
        }
    }

    public void doLayerUp() {
        if (mSelectIndex != -1) {
            if (mSelectIndex != mBeans.size() - 1) {
                ContainerBean remove = mBeans.remove(mSelectIndex);
                mBeans.addLast(remove);
                mSelectIndex = mBeans.size() - 1;
                refresh();
            }
        }
    }

    public void doLayerDown() {
        if (mSelectIndex != -1) {
            if (mSelectIndex != 0) {
                ContainerBean remove = mBeans.remove(mSelectIndex);
                mBeans.addFirst(remove);
                mSelectIndex = 0;
                refresh();
            }
        }
    }

    /**
     * 清除所有的
     */
    public void reset() {
        if (mIsInit) {
            for (ContainerBean bean : mBeans) {
                bean.onDestroy();
            }
            mBeans.clear();
            mSelectIndex = -1;
            refresh();
            if (rotateAnimator != null) {
                rotateAnimator.cancel();
            }
            if (mListener != null) {
                mListener.onNeedSaveChangedTo(false);
            }
            if (null != mAttacher) {
                mAttacher.update();
            }
            LocalStickerData.getInstance().clearBitmapCache();
        }
    }

    //重置bean参数
    public void resetParam() {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).resetParam();
            refresh();
        }
    }

    public void setShowSrc(boolean showSrc) {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setShowSrc(showSrc);
            refresh();
        }
    }

    public void resetPaint() {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).resetPaint();
            refresh();
        }
    }

    public void cancelSettingMode() {
        mIsSettingMode = false;
        for (ContainerBean bean : mBeans) {
            if (bean instanceof EditEmojiBean) {
                ((EditEmojiBean) bean).reset();
            }
        }
        refresh();
    }

    public void saveSettingMode() {
        mIsSettingMode = false;
        for (ContainerBean bean : mBeans) {
            if (bean instanceof EditEmojiBean) {
                ((EditEmojiBean) bean).save();
            }
        }
        refresh();
    }

    public void saveParam() {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).saveParam();
            refresh();
        }
    }

    public void removeLastParam() {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).removeLastParam();
            refresh();
        }
    }

    public void removeLastPaint() {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).removeLastPaint();
            refresh();
        }
    }

    public ContainerBean getCurrentBean() {
        if (mSelectIndex != -1) {
            return mBeans.get(mSelectIndex);
        } else {
            return null;
        }
    }

    public void updateTone(float tone) {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setTone(tone);
        }
        refresh();
    }

    public void updateSaturation(float st) {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setSaturation(st);
        }
        refresh();
    }

    public void updateBrightness(float bn) {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setBrightness(bn);
            refresh();
        }
    }

    public void updateAlpha(float a) {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setAlpha(a);
            refresh();
        }
    }

    public void updatePaintWidthProgress(int progress) {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setPaintWidth(progress);
            refresh();
        }
    }

    public void setPaintMode(int mode) {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setPaintMode(mode);
        }
    }

    public void setPaintStyle(int style) {
        ContainerBean canvasBean = mBeans.get(mSelectIndex);
        if (canvasBean != null && canvasBean.getType() == ContainerView.BEAN_TYPE_STICKER) {
            ((EditEmojiBean) canvasBean).setPaintStyle(style);
        }
    }

    public float getCenterX() {
        return centerX;
    }

    public float getCenterY() {
        return centerY;
    }

    public boolean hasGif() {
        boolean hasGif = false;
        for (ContainerBean bean : mBeans) {
            if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
                hasGif = true;
                break;
            }
        }
        return hasGif;
    }

    public int getDuration() {
        int maxDuration = 0;
        for (ContainerBean bean : mBeans) {
            if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
//                int duration = ((StickerGifBean) bean).getDuration();
//                if (duration > maxDuration) {
//                    maxDuration = duration;
//                }
            }
        }
        if (maxDuration == 0) {
            return maxDuration;
        }
        while (maxDuration < 1000) {
            maxDuration *= 2;
        }
        return maxDuration;
    }

    public float getFrame() {
        float maxFrame = 0;
        for (ContainerBean bean : mBeans) {
            if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
//                float frame = ((StickerGifBean) bean).getFrame();
//                if (frame > maxFrame) {
//                    maxFrame = frame;
//                }
            }
        }
        return maxFrame;
    }

    public void stopGif() {
        for (ContainerBean bean : mBeans) {
            if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
//                ((StickerGifBean) bean).stop();
            }
        }
    }

    public void startGif() {
        for (ContainerBean bean : mBeans) {
            if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
//                ((StickerGifBean) bean).start();
            }
        }
    }

    /**
     * 用于获取合成好的图片
     * mDrawableRect 是放大后的 Rect  ,Emoji的效果也是放大后的所以需要这样
     *
     * @return
     */
    public Bitmap getDstBitmap(int position) {
        if (mSrcBitmap != null && !mSrcBitmap.isRecycled()) {
            Matrix matrix1 = this.getImageMatrix();
            float[] values1 = new float[10];
            matrix1.getValues(values1);
            if (mCacheBitmap == null || (mSrcBitmap.getWidth() != mCacheBitmap.getWidth() || mSrcBitmap.getHeight() != mCacheBitmap.getHeight())) {
                mCacheBitmap = Bitmap.createBitmap(mSrcBitmap.getWidth(), mSrcBitmap.getHeight(), Config.ARGB_8888);
            }
            Canvas canvas = new Canvas(mCacheBitmap);
            Paint p = new Paint(Paint.ANTI_ALIAS_FLAG);
            p.setAntiAlias(true);
            p.setFilterBitmap(true);

            canvas.drawBitmap(mSrcBitmap, 0, 0, p);
            int len = mBeans.size();

            RectF cacheRect = new RectF();
            for (int i = 0; i < len; i++) {
                ContainerBean bean = mBeans.get(i);
                RectF dst = bean.getRect();
                cacheRect.left = dst.left - mDrawableRect.left;
                cacheRect.top = dst.top - mDrawableRect.top;
                cacheRect.right = dst.right - mDrawableRect.left;
                cacheRect.bottom = dst.bottom - mDrawableRect.top;
                canvas.save();
                canvas.scale(1 / values1[0], 1 / values1[4]);
                canvas.rotate(bean.getDegree(), cacheRect.centerX(), cacheRect.centerY());
                canvas.scale(bean.getFlipX(), bean.getFlipY(), cacheRect.centerX(), cacheRect.centerY());
                if (bean.getType() == ContainerView.BEAN_TYPE_GIF) {
//                    canvas.drawBitmap(((StickerGifBean) bean).seekToPositionAndGet(position % ((StickerGifBean) bean).getDuration()), null, cacheRect, p);
                } else {
                    canvas.drawBitmap(bean.getBitmap(), null, cacheRect, p);
                }
                canvas.restore();

            }

            return mCacheBitmap;
        }
        return mSrcBitmap;
    }

    public void releaseCacheBitmap() {
        mCacheBitmap = null;
    }

//    @Override
//    public Bitmap getCurrentBitmap(long timestamp) {
//        return getDstBitmap((int) timestamp);
//    }

    public RectF getDrawableRect() {
        return mDrawableRect;
    }

    public void setHaveSetting(boolean haveSetting) {
        mHaveSetting = haveSetting;
    }

    public void setStickerEditListener(StickerEditListener stickerEditListener) {
        mStickerEditListener = stickerEditListener;
    }

    public void setStickerEditSettingListener(StickerEditSettingListener stickerEditSettingListener) {
        mStickerEditSettingListener = stickerEditSettingListener;
    }

//    @Override
//    public void onRefresh() {
//        refresh();
//    }

    public interface StickerEditListener {

        void onClickSetting();

    }

    public interface StickerEditSettingListener {

        void onSelectOther(ContainerBean bean);

        void onPaintFinish();

    }


    /**
     * 回调
     *
     * @param listener
     */
    public void setListener(ICanvasEditListener listener) {
        mListener = listener;
    }

    public boolean isHasPopView() {
        return mHasPopView;
    }

    public void setHasPopView(boolean hasPopView) {
        mHasPopView = hasPopView;
    }

    public void refresh() {
        if (!mHandler.hasMessages(DO_ON_DRAW)) {
            mHandler.sendEmptyMessage(DO_ON_DRAW);
        }
    }


    ///########################################

    @Override
    public void setPhotoViewRotation(float rotationDegree) {
        mAttacher.setRotationTo(rotationDegree);
    }

    @Override
    public void setRotationTo(float rotationDegree) {
        mAttacher.setRotationTo(rotationDegree);
    }

    @Override
    public void setRotationBy(float rotationDegree) {
        mAttacher.setRotationBy(rotationDegree);
    }

    @Override
    public boolean canZoom() {
        return mAttacher.canZoom();
    }

    @Override
    public RectF getDisplayRect() {
        return mAttacher.getDisplayRect();
    }

    @Override
    public Matrix getDisplayMatrix() {
        return mAttacher.getDrawMatrix();
    }

    @Override
    public boolean setDisplayMatrix(Matrix finalRectangle) {
        return mAttacher.setDisplayMatrix(finalRectangle);
    }

    @Override
    @Deprecated
    public float getMinScale() {
        return getMinimumScale();
    }

    @Override
    public float getMinimumScale() {
        return mAttacher.getMinimumScale();
    }

    @Override
    @Deprecated
    public float getMidScale() {
        return getMediumScale();
    }

    @Override
    public float getMediumScale() {
        return mAttacher.getMediumScale();
    }

    @Override
    @Deprecated
    public float getMaxScale() {
        return getMaximumScale();
    }

    @Override
    public float getMaximumScale() {
        return mAttacher.getMaximumScale();
    }

    @Override
    public float getScale() {
        return mAttacher.getScale();
    }

    @Override
    public ScaleType getScaleType() {
        return mAttacher.getScaleType();
    }

    @Override
    public void setAllowParentInterceptOnEdge(boolean allow) {
        mAttacher.setAllowParentInterceptOnEdge(allow);
    }

    @Override
    @Deprecated
    public void setMinScale(float minScale) {
        setMinimumScale(minScale);
    }

    @Override
    public void setMinimumScale(float minimumScale) {
        mAttacher.setMinimumScale(minimumScale);
    }

    @Override
    @Deprecated
    public void setMidScale(float midScale) {
        setMediumScale(midScale);
    }

    @Override
    public void setMediumScale(float mediumScale) {
        mAttacher.setMediumScale(mediumScale);
    }

    @Override
    @Deprecated
    public void setMaxScale(float maxScale) {
        setMaximumScale(maxScale);
    }

    @Override
    public void setMaximumScale(float maximumScale) {
        mAttacher.setMaximumScale(maximumScale);
    }


    @Override
    public void setImageResource(int resId) {
        super.setImageResource(resId);
        if (null != mAttacher) {
            mAttacher.update();
        }
    }

    @Override
    public void setImageURI(Uri uri) {
        super.setImageURI(uri);
        if (null != mAttacher) {
            mAttacher.update();
        }
    }

    @Override
    public void setOnMatrixChangeListener(CanvasPhotoViewAttacher.OnMatrixChangedListener listener) {
        mAttacher.setOnMatrixChangeListener(listener);
    }

    @Override
    public void setOnLongClickListener(OnLongClickListener l) {
        mAttacher.setOnLongClickListener(l);
    }

    @Override
    public void setOnPhotoTapListener(CanvasPhotoViewAttacher.OnPhotoTapListener listener) {
        mAttacher.setOnPhotoTapListener(listener);
    }

    @Override
    public CanvasPhotoViewAttacher.OnPhotoTapListener getOnPhotoTapListener() {
        return mAttacher.getOnPhotoTapListener();
    }

    @Override
    public void setOnViewTapListener(CanvasPhotoViewAttacher.OnViewTapListener listener) {
        mAttacher.setOnViewTapListener(listener);
    }

    @Override
    public CanvasPhotoViewAttacher.OnViewTapListener getOnViewTapListener() {
        return mAttacher.getOnViewTapListener();
    }

    @Override
    public void setScale(float scale) {
        mAttacher.setScale(scale);
    }

    @Override
    public void setScale(float scale, boolean animate) {
        mAttacher.setScale(scale, animate);
    }

    @Override
    public void setScale(float scale, float focalX, float focalY, boolean animate) {
        mAttacher.setScale(scale, focalX, focalY, animate);
    }

    @Override
    public void setScaleType(ScaleType scaleType) {
        if (null != mAttacher) {
            mAttacher.setScaleType(scaleType);
        }
    }

    @Override
    public void setZoomable(boolean zoomable) {
        mAttacher.setZoomable(zoomable);
    }

    @Override
    public Bitmap getVisibleRectangleBitmap() {
        return mAttacher.getVisibleRectangleBitmap();
    }

    @Override
    public void setZoomTransitionDuration(int milliseconds) {
        mAttacher.setZoomTransitionDuration(milliseconds);
    }

    @Override
    public IPhotoView getIPhotoViewImplementation() {
        return mAttacher;
    }

    @Override
    public void setOnDoubleTapListener(GestureDetector.OnDoubleTapListener newOnDoubleTapListener) {
        mAttacher.setOnDoubleTapListener(newOnDoubleTapListener);
    }

    @Override
    public float getBaseScale() {
        return mAttacher.getBaseScale();
    }

    @Override
    protected void onDetachedFromWindow() {
        mAttacher.cleanup();
        super.onDetachedFromWindow();
    }

    /**
     * 初始化后显示的Drawable
     */
    private RectF mSupportDrawableRect;

    /**
     * 这个是图片的Bounds Drawable
     */
    private RectF mBaseDrawableRect;

    /**
     * 这个方法要在Init后调用
     */
    private void countDrawableInitPosition(RectF viewRect) {
        mSupportDrawableRect = new RectF();
        float width = mSrcBitmap.getWidth();
        float height = mSrcBitmap.getHeight();

        float vW = viewRect.width();
        float vH = viewRect.height();

        float w, h;

        if (width / height > vW / vH) {//宽顶着
            w = vW;
            h = w / width * height;
        } else {//高顶着
            h = vH;
            w = h / height * width;
        }

        mSupportDrawableRect.left = (vW - w) / 2 + viewRect.left;
        mSupportDrawableRect.top = (vH - h) / 2 + viewRect.top;
        mSupportDrawableRect.right = mSupportDrawableRect.left + w;
        mSupportDrawableRect.bottom = mSupportDrawableRect.top + h;
    }

    private void countScaleAndDo() {
        int len = mBeans.size();
        for (int i = 0; i < len; i++) {
            ContainerBean bean = mBeans.get(i);
            bean.doScaleMove(mBaseDrawableRect, mSupportDrawableRect, getImageMatrix(), mCacheMatrix, mRect);
        }
    }

    public boolean isInit() {
        return mIsInit;
    }
}
